<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="设备编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['code']" placeholder="请输入设备编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name']" placeholder="请输入设备名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['mode']" placeholder="请输入设备型号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--<a-input v-decorator="['categoryId', validatorRules.categoryId]" placeholder="请输入设备类型"></a-input>-->
              <a-select v-decorator="['categoryId', validatorRules.categoryId]" placeholder="请选择设备类型">
                <a-select-option :key="item.id" v-for="item in categoryList" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--<a-input v-decorator="['status']" placeholder="请输入设备状态"></a-input>-->
              <j-dict-select-tag placeholder="请选择设备状态" :triggerChange="true" v-decorator="['status']"
                                 dictCode="equipment_status"
                                 style="width: 200px"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="检定单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['verificationUnit']" placeholder="请输入检定单位"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="单位名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['unitName']" placeholder="请输入单位名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['responsible']" placeholder="请输入负责人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备用途" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['equipmentUse']" placeholder="请输入设备用途"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="存放位置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['location']" placeholder="请输入存放位置"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择生产日期" v-decorator="['productionDate']" :trigger-change="true"
                      style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="入库" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择入库" v-decorator="['putDateTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="出厂日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择出厂日期" v-decorator="['manufactureDate']" :trigger-change="true"
                      style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="有效期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择有效期" v-decorator="['validityDate']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="出厂编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['manufactureNo']" placeholder="请输入出厂编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['provider']" placeholder="请输入供应商"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="制造商" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['manufacturer']" placeholder="请输入制造商"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['description']" placeholder="请输入描述"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <p align="center" style="font-weight: bold ;color: #1890ff">技术参数:</p>
          </a-col>
          <a-col :span="24">
            <div class="dynamic-wrap">
              <a-row :gutter="24">

                <a-col :span="6">
                  <p align="center" style="font-weight: bold">参数名称</p>
                </a-col>

                <a-col :span="3">
                  <p align="center" style="font-weight: bold">描述</p>
                </a-col>

                <a-col :span="3">
                  <p align="center" style="font-weight: bold">标准值</p>
                </a-col>

                <a-col :span="3">
                  <p align="center" style="font-weight: bold">上限值</p>
                </a-col>

                <a-col :span="3">
                  <p align="center" style="font-weight: bold">下限值</p>
                </a-col>

                <a-col :span="3">
                  <p align="center" style="font-weight: bold">备注</p>
                </a-col>

                <a-col :span="3" style="padding-left: 0px">
                  <p  style="font-weight: bold">删除一行</p>
                </a-col>
              </a-row>

              <div v-for="(item,index) in keysList" :key="index">
                <a-row :gutter="24">
                  <!--<span>{{item}}</span>-->
                  <a-col :span="6">
                    <a-input v-model="item[index+'paramName']"/>
                  </a-col>

                  <a-col :span="3">
                    <a-input v-model="item[index+'description']"/>
                  </a-col>

                  <a-col :span="3">
                    <a-input v-model="item[index+'standard']"/>
                  </a-col>

                  <a-col :span="3">
                    <a-input v-model="item[index+'ceil']"/>
                  </a-col>

                  <a-col :span="3">
                    <a-input v-model="item[index+'lower']"/>
                  </a-col>

                  <a-col :span="3">
                    <a-input v-model="item[index+'remark']"/>
                  </a-col>

                  <a-col :span="3" style="padding-left: 0px">
                    <template v-if="keysList.length >= 1">
                      <a-button type="dashed" icon="minus" @click="removeRow(item)"
                                class="minusRowBtn"></a-button>
                    </template>
                  </a-col>
                </a-row>
              </div>
              <a-button type="dashed" icon="plus" @click="addRow" class="addRowBtn">
                新增技术参数
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import {httpAction, getAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'

  export default {
    name: 'EquipmentForm',
    components: {
      JFormContainer,
      JDate,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: () => {
        },
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data() {
      return {
        //动态表单参数
        keysList: [
          {
            "0paramName": '',
            "0description": '',
            "0standard": '',
            "0ceil": '',
            "0lower": '',
            "0remark": '',
          }
        ],

        form: this.$form.createForm(this),
        //设备类型列表
        categoryList: [],
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {
          categoryId: {
            rules: [
              {required: true, message: '请选择设备类型!'},
            ]
          },
        },
        url: {
          getType: "/equipment/equipment/getEquipmentType",
          add: "/equipment/equipment/add",
          edit: "/equipment/equipment/edit",
          queryById: "/equipment/equipment/queryById"
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created() {
      this.technologyParamForm = this.$form.createForm(this),
        //如果是流程中表单，则需要加载流程表单data
        this.showFlowData();
      //加载设备类型列表
      this.getCategoryList();
    },
    methods: {
      // 移除某行
      removeRow(k) {
        if (this.keysList.length === 0) { // 如果存在可以移除所有行的情况，把条件改为this.keysList.length === 0即可
          return
        }
        this.keysList = this.keysList.filter(item => item !== k)
      },
      // 新增一行
      addRow() {
        // this.id = this.id + 1;
        // this.keysList = this.keysList.concat(this.id);
        const prefix = this.keysList.length;
        this.keysList.push({
          [prefix + "paramName"]: '',
          [prefix + "description"]: '',
          [prefix + "standard"]: '',
          [prefix + "ceil"]: '',
          [prefix + "lower"]: '',
          [prefix + "remark"]: '',
        })
      },
      //获取设备分类列表
      getCategoryList() {
        getAction(this.url.getType).then(res => {
          if (res.success) {
            //console.log(res);
            this.categoryList = res.result;
          }
        })
      },
      add() {
        this.edit({});
      },
      edit(record) {
        let List = [];
        //console.log(record.technologyParam);
        if (record.technologyParam) {
          List = JSON.parse(record.technologyParam);
        }
        //console.log(List);
        let technologyParamFormData = [];
        List.forEach((obj, index) => {
          const prefix = index;
          technologyParamFormData.push({
            [prefix + "paramName"]: obj.paramName,
            [prefix + "description"]: obj.description,
            [prefix + "standard"]: obj.standard,
            [prefix + "ceil"]: obj.ceil,
            [prefix + "lower"]: obj.lower,
            [prefix + "remark"]: obj.remark,
          })
        })
        this.keysList = technologyParamFormData;
        console.log(this.keysList);

        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'code', 'name', 'mode', 'categoryId', 'status', 'verificationUnit', 'unitName', 'responsible', 'equipmentUse', 'location', 'productionDate', 'putDateTime', 'manufactureDate', 'validityDate', 'manufactureNo', 'provider', 'manufacturer', 'description', 'technologyParam'))
        })
      },
      //渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = {id: this.formData.dataId};
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm() {
        let technologyParamFormData = [];
        this.keysList.forEach((obj, index) => {
          let tempObj = {
            paramName: obj[index + 'paramName'],
            description: obj[index + 'description'],
            standard: obj[index + 'standard'],
            ceil: obj[index + 'ceil'],
            lower: obj[index + 'lower'],
            remark: obj[index + 'remark']
            //...
          }
          technologyParamFormData.push(tempObj)
        })
        const submitArray = technologyParamFormData.filter(temp => {
          const filterArray = Object.values(temp).filter(t => t !== '')
          return filterArray.length > 0
        })
        console.log(JSON.stringify(submitArray));
        let technologyParam = JSON.stringify(submitArray);
        const that = this;
        //触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.technologyParam = technologyParam;
            console.log("表单提交数据:", formData);
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'code', 'name', 'mode', 'categoryId', 'status', 'verificationUnit', 'unitName', 'responsible', 'equipmentUse', 'location', 'productionDate', 'putDateTime', 'manufactureDate', 'validityDate', 'manufactureNo', 'provider', 'manufacturer', 'description', 'technologyParam'))
      },
    }
  }
</script>
<style lang="less" scoped>
  .dynamic-wrap {
    padding-top: 10px;
    background-color: white;
    overflow-y: scroll;
    overflow-x: hidden;

    &::-webkit-scrollbar {
      width: 7px;
    }

    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
      border-radius: 10px;
    }

    &::-webkit-scrollbar-track-piece {
      background: transparent;
    }
  }

  .minusRowBtn {
    color: #f5222d;
    background: #fff1f0;
    border-color: #ffa39e;
    padding-right: 7px;
    padding-left: 7px;
    height: 29px;
    margin-left: 10px;
  }

  .addRowBtn {
    width: 100%;
    color: #1890ff;
    border-color: #91d5ff;
    margin: 0px 0px 0px 0px;
  }
</style>